import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../base/Constant.dart';
// import 'package:panda/base/SignType.dart';
import '../../base/application.dart';
import '../../event/LoginEvent.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../util/LoadingUtil.dart';
import '../../util/SignUtil.dart';

class BindZfbPage extends StatefulWidget {
  BindZfbPage({Key key}) : super(key: key);

  @override
  _BindZfbPageState createState() => _BindZfbPageState();
}

class _BindZfbPageState extends State<BindZfbPage> {
  String codeString = "获取验证码";
  int codeStatus = 1;
  Timer _countdownTimer;
  String token = "";
  int _countdownNum = 59;
  String code = "", account = "", name = "", truename = "";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
    });
    truename = APPLIC.userInfoMap['user_msg']['alipay_account'];
    setState(() {});
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text(
          '绑定支付宝',
          style: TextStyle(
              color: black,
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
        ),
        elevation: 0.2,
        backgroundColor: white,
        iconTheme: new IconThemeData(color: black_99),
        brightness: Brightness.light,
      ),
      body: new Container(
          width: double.infinity,
          color: white,
          child: new Column(children: <Widget>[
            Container(
                width: double.infinity,
                color: f0Color,
                padding:
                    EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
                child: Text(
                  '已绑定支付宝:' +
                      ('$truename' == null || '$truename' == 'null'
                          ? ''
                          : '$truename'),
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      color: Colors.black54),
                )),
            Container(
              padding: EdgeInsets.only(
                  top: ScreenUtil.getInstance().setHeight(DP_15),
                  left: ScreenUtil.getInstance().setHeight(DP_20),
                  right: ScreenUtil.getInstance().setHeight(DP_20)),
              child: Row(children: <Widget>[
                new Expanded(
                    child: new TextField(
                  keyboardAppearance: Brightness.light,
                  keyboardType: TextInputType.numberWithOptions(),
                  maxLines: 1,
                  onChanged: (value) {
                    code = value;
                  },
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                  cursorColor: mainColor,
                  decoration: new InputDecoration(
                      hintText: "短信验证码",
                      border: InputBorder.none,
                      hintStyle: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                )),
                new Container(
                  width: ScreenUtil.getInstance().setWidth(DP_200 + 5),
                  height: ScreenUtil.getInstance().setHeight(DP_50),
                  margin: EdgeInsets.fromLTRB(0, 0, 0, 8),
                  decoration: new BoxDecoration(
                      color: codeStatus == 0
                          ? Color.fromARGB(255, 99, 99, 99)
                          : mainColor,
                      borderRadius: BorderRadius.circular(20.0)),
                  child: new FlatButton(
                    child: new Padding(
                      padding: EdgeInsets.all(0.0),
                      child: new Text(
                        "$codeString",
                        style: new TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE)),
                      ),
                    ),
                    onPressed: () {
                      // if (codeStatus == 0) {
                      //   return;
                      // }
                      // if (userController.text.isEmpty) {
                      //   Fluttertoast.showToast(msg: "请输入手机号");
                      //   return;
                      // }
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (_) {
                            return new NetLoadingDialog(
                              loadingText: "获取中...",
                              bgColor: Color.fromARGB(255, 0, 0, 0),
                              requestCallBack: null,
                              outsideDismiss: false,
                            );
                          });
                      getPhoneCode();
                    },
                  ),
                )
              ]),
            ),
            Container(height: 1, color: f0Color),
            Container(
              padding: EdgeInsets.only(
                  top: ScreenUtil.getInstance().setHeight(DP_10),
                  left: ScreenUtil.getInstance().setHeight(DP_20),
                  right: ScreenUtil.getInstance().setHeight(DP_20)),
              child: Row(children: <Widget>[
                new Expanded(
                    child: new TextField(
                  keyboardAppearance: Brightness.light,
                  // keyboardType: TextInputType.numberWithOptions(),
                  maxLines: 1,
                  onChanged: (value) {
                    account = value;
                  },
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                  cursorColor: mainColor,
                  decoration: new InputDecoration(
                      hintText: "支付宝账号",
                      border: InputBorder.none,
                      hintStyle: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                )),
              ]),
            ),
            Container(height: 1, color: f0Color),
            Container(
              padding: EdgeInsets.only(
                  top: ScreenUtil.getInstance().setHeight(DP_10),
                  left: ScreenUtil.getInstance().setHeight(DP_20),
                  right: ScreenUtil.getInstance().setHeight(DP_20)),
              child: Row(children: <Widget>[
                new Expanded(
                    child: new TextField(
                  keyboardAppearance: Brightness.light,
                  // keyboardType: TextInputType.numberWithOptions(),
                  maxLines: 1,
                  onChanged: (value) {
                    name = value;
                  },
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                  cursorColor: mainColor,
                  decoration: new InputDecoration(
                      hintText: "真实姓名(与支付宝对应)",
                      border: InputBorder.none,
                      hintStyle: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                )),
              ]),
            ),
            Container(height: 1, color: f0Color),
            new Container(
              width: double.infinity,
              margin: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_50)),
              height: ScreenUtil.getInstance().setWidth(DP_90),
              decoration: new BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(DP_80)),
              padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
              child: new FlatButton(
                child: new Padding(
                  padding: EdgeInsets.all(0.0),
                  child: new Text(
                    "立即绑定",
                    style: new TextStyle(
                        color: Colors.white,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                  ),
                ),
                onPressed: () {
                  if (code == "") {
                    Fluttertoast.showToast(msg: "请填写验证码");
                    return;
                  }
                  if (account == "") {
                    Fluttertoast.showToast(msg: "请填写支付宝账号");
                    return;
                  }
                  if (name == "") {
                    Fluttertoast.showToast(msg: "请填写姓名");
                    return;
                  }
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) {
                        return new NetLoadingDialog(
                          loadingText: "绑定中...",
                          bgColor: Color.fromARGB(255, 0, 0, 0),
                          requestCallBack: null,
                          outsideDismiss: false,
                        );
                      });
                  bind();
                  // _checkSub(context);
                },
              ),
            )
          ])),
    );
  }

  getPhoneCode() async {
    Map map = new Map();
    map['token'] = token;
    map['sign_type'] = createSignType(
        Api.BaseUrl + '/index.php/wap/UserBalance/sendAlipayCode');
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + '/index.php/wap/UserBalance/sendAlipayCode',
        data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      setState(() {
        codeStatus = 0;
        if (_countdownTimer != null) {
          return;
        }
        codeString = '${_countdownNum--}重新获取';
        _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
          setState(() {
            if (_countdownNum > 0) {
              codeStatus = 0;
              codeString = '${_countdownNum--}重新获取';
            } else {
              codeString = '获取验证码';
              codeStatus = 1;
              _countdownNum = 59;
              _countdownTimer.cancel();
              _countdownTimer = null;
            }
          });
        });
      });
    }
  }

  bind() async {
    Map map = new Map();
    map['token'] = token;
    map['truename'] = name;
    map['alipay_account'] = account;
    map['code'] = code;
    map['sign_type'] =
        createSignType(Api.BaseUrl + '/index.php/wap/UserBalance/changeAlipay');
    print(map);
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + '/index.php/wap/UserBalance/changeAlipay',
        data: getSign(map));
    Map userMap = json.decode(response.data);
    int result = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (result == 1 && mounted) {
      APPLIC.eventBus.fire(LoginEvent());
      Navigator.of(context).pop(name + "," + account);
    }
  }
}
